<?php

// +----------------------------------------------------------------------

namespace app\api\controller;

use app\common\controller\Api;
use app\mall\model\Order as OrderModel;
use util\Wxsdk;
use wxpay\PayVthree;
use aliutil\Auth as AliPay;
use think\Db;
/**
 * 支付通知控制器
 * @package app\api\controller
 */
class Notify extends Api
{

	/**
	 * @微信支付通知
	 */
	public function wechat($id = 1)
	{
		if (request()->isPost()) {
			// 获取数据
			$data = file_get_contents("php://input");
			$result['title'] = '微信支付通知'; 
			$result['head'] = request()->header();
			// 验证签名
			$pay = new PayVthree(true, $id);
			$result['resign'] = $pay->verify($data, $result['head']);
			if ($result['resign'] === false){
				$result['body'] = $data;
				$result['resign'] = $pay->getError(); 
				trace($result, 'error'); // 验证不通过记录错误日志
			}
			// 解密数据
			$data = \json_decode($data, true);
			$res = $pay->aes($data['resource']['associated_data'], $data['resource']['nonce'], $data['resource']['ciphertext']);
			
			if ($res === false){
				$result['res'] = $res;
				trace($result, 'error'); // 解密失败记录错误日志
			}
			// 处理订单信息
			$orderModel = new OrderModel;
			$orderModel->notify(json_decode($res, true), 'wechat');
			return json(['code' => 'SUCCESS', 'message' => '成功']);
		}else{
			return json(['code' => 'SUCCESS', 'message' => '连接成功']);
		}
	}
	
	/**
	 * @支付宝支付通知
	 */
	public function alipay()
	{
		if (request()->isPost()) {
			// 获取数据
			$data = request()->param();
			// 验证签名
			$pay = new AliPay();
			$result['resign'] = $pay->rsaCheck($data);
			if ($result['resign'] === false){
				$result['title'] = '支付宝支付通知';
				$result['head'] = request()->header();
				$result['body'] = $data;
				trace($result, 'error'); // 验证不通过记录错误日志
				return 'fail';
			}
			// 处理订单信息
			$orderModel = new OrderModel;
			$return = $orderModel->notify($data, 'alipay');
			if ($return === false) {
				$result['title'] = '支付宝支付通知';
				$result['head'] = request()->header();
				$result['body'] = $data;
				$result['error'] = $orderModel->getError(); 
				trace($result, 'error'); // 验证不通过记录错误日志
				return 'fail';
			} else {
				return 'success';
			}
		}else{
			return json(['code' => 'SUCCESS', 'message' => '连接成功']);
		}
	}
}
